import { Controller, Post, Body, Logger } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';
import { AppException } from '../exceptions/AppException';
import { HttpStatusCodeEnum } from '../enums/http-status-code.enum';
import { Public } from './auth.decorator';
import { RedisService } from '../redis/redis.service';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import * as path from 'node:path';

@Controller('auth')
@ApiTags('权限验证') // 为控制器添加标签
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly redisService: RedisService,
  ) {}

  private readonly logger = new Logger(AuthController.name);

  @Post('login')
  @Public()
  @ApiOperation({ summary: '用户登录' })
  async login(@Body() body: LoginDto) {
    const { username, password } = body;

    // 验证用户身份
    const user = await this.authService.validateUser(username, password);
    if (!user) {
      // 获取当前文件的文件名
      const fileName = path.basename(__filename);

      // 在日志中添加文件名信息
      this.logger.error(`用户名或密码验证失败, 当前文件: ${fileName}`);
      throw new AppException(HttpStatusCodeEnum.UNAUTHORIZED); // 身份验证失败
    }

    // 生成 JWT token
    const payload = { username: user.username, sub: user.id }; // 使用用户 ID 作为 sub
    const token = await this.authService.generateToken(payload);
    // 将token和用户信息存储在redis中
    await this.redisService.set(`accessToken${user.id}`, token);
    await this.redisService.set(`userInfo${user.id}`, JSON.stringify(user));

    return { access_token: token }; // 返回生成的 JWT
  }
}
